﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using TencentCloud.Ame.V20190916.Models;
using TencentCloud.Cwp.V20180228.Models;
using ZenSystemService.Api.Common;
using ZenSystemService.Api.Common.Encryption;
using ZenSystemService.Api.Data;
using ZenSystemService.Api.Domain;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.DTOs.Institution;
using ZenSystemService.Api.DTOs.Users;
using ZenSystemService.Api.Entities;

namespace ZenSystemService.Api.Services
{
    public class InstitutionService
    {
        private readonly ApplicationDbContext _context;
        private IMapper _mapper;
        private const string DefaultInstitutionAdminPassword = "123456";
        private readonly IEncryptionService _encrytionService;

        public InstitutionService(ApplicationDbContext context, IMapper mapper,IEncryptionService encryptionService)
        {
            _context = context;
            _mapper = mapper;
            _encrytionService = encryptionService;
        }

        public async Task<IEnumerable<Institution>> GetAllInstitutionsAsync(UserModel user)
        {
            if (user.IsSuperAdmin)
                return await _context.Institutions.ToListAsync();
            return await _context.Institutions.Where(i => i.InstitutionId == user.InstitutionId).ToListAsync();
        }

        public async Task<Institution> GetInstitutionByIdAsync(int id)
        {
            return await _context.Institutions.FindAsync(id);
        }

        public bool CreateInstitutionAsync(ref Institution institution)
        {
            _context.Institutions.Add(institution);
            int count = _context.SaveChanges();
            return count > 0 ? true : false;
        }

        public async Task<InstitutionDTO> CreateInstitutionAsync(InstitutionDTO institutionDTO)
        {
            var institution = _mapper.Map<Institution>(institutionDTO);
            var existed = await _context.Institutions.FirstOrDefaultAsync(x => x.Name == institutionDTO.Name);
            if (existed == null)
            {
                await _context.Institutions.AddAsync(institution);
                _context.SaveChanges();
            }
            
            return _mapper.Map<InstitutionDTO>(institution);
        }

        public async Task<UserCreateResultDTO> CreateInstitutionAsync(InstitutionCreateRequestDTO institutionDTO)
        {
            var institution = _mapper.Map<Institution>(institutionDTO);
            var existed = await _context.Institutions.FirstOrDefaultAsync(x => x.Name == institutionDTO.Name);
            if (existed == null)
            {
                await _context.Institutions.AddAsync(institution);
                _context.SaveChanges();
                var admin = new User
                {
                    Username = $"Admin_{institution.InstitutionId}",
                    PasswordHash = BCrypt.Net.BCrypt.HashPassword(DefaultInstitutionAdminPassword),
                    EncryptedPassword = _encrytionService.Encrypt(DefaultInstitutionAdminPassword),
                    Institution = institution,
                    UserType = UserType.DefaultAdmin.ToString(),
                };
                await _context.Users.AddAsync(admin);
                _context.SaveChanges();
                return _mapper.Map<UserCreateResultDTO>(admin);
            }
            return null;
        }

        public async Task<bool> UpdateInstitutionAsync(Institution institution)
        {
            _context.Entry(institution).State = EntityState.Modified;
            int count = await _context.SaveChangesAsync();
            return count > 0 ? true : false;
        }

        public async Task<bool> DeleteInstitutionAsync(int id)
        {
            var institution = await _context.Institutions.FindAsync(id);
            if (institution != null)
            {
                _context.Institutions.Remove(institution);
                int count=await _context.SaveChangesAsync();
                return count > 0 ? true : false;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 根据手机号得到机构实体信息
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public async Task<Institution> GetInstitutionByPhoneAsync(string phone)
        {
            return await _context.Institutions.SingleOrDefaultAsync(u => u.PhoneNo == phone && u.Enabled == "1");

        }
    }
}